<?php

namespace app\modules\Member\models;

use Yii;
use yii\web\Session;
use dektrium\user\models\User;

/**
 * This is the model class for table "member".
 *
 * @property integer $id
 * @property string $name
 * @property string $phone
 * @property string $mail
 * @property string $password
 * @property string $address
 * @property string $position
 * @property string $group
 * @property integer $dist_id
 * @property integer $type
 * @property string $desc
 * @property integer $status
 * @property string $created_at
 * @property string $updated_at
 * @property integer $gender
 */
class Member extends \yii\db\ActiveRecord
{
    public $confirmPassword;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'member';
    }

    public function scenarios()
    {
		$scenarios = parent::scenarios();

        $scenarios['save'] = ['openId'];
        $scenarios['create'] =  ['name','phone', 'mail', 'password', 'address','gender','position','group','dist_id','type','desc','status','company'];
        $scenarios['update'] = ['name','phone', 'mail', 'password', 'address','gender','position','group','dist_id','type','desc','status','company']; 
        $scenarios['password'] = ['password', 'confirmPassword'];
        $scenarios['login']  = ['phone', 'password','openId'];
        $scenarios['register']  = ['company','name','phone','mail','password','confirmPassword'];
        return $scenarios;
    }
    

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['phone','password','mail','name','company','confirmPassword'], 'required','on' => 'register'],
            [['mail'], 'email','on' => 'register'],
            [['confirmPassword'], 'required','message'=>'确认密码不能为空',],
            [['phone','password'], 'required'],
            [['dist_id', 'type', 'status', 'gender'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['name'], 'string', 'max' => 32],
            [['phone', 'position'], 'string', 'max' => 64],
            [['mail', 'password', 'address','company'], 'string', 'max' => 255],
            [['group', 'desc'], 'string', 'max' => 128],
            [['confirmPassword'], 'compare','compareAttribute'=>'password', 'message'=>'确认密码输入有误','on' => ['register','password']],
             [['phone'], 'unique'],
            //[['confirmPassword'], 'validateConPassword','on' => 'register'],
        ];
    }


     // 保存前处理
    public function beforeSave($insert) {//{{{
        if($insert){
            $this->created_at = date("Y-m-d H:i:s");

			// 将数据同步至管理员表  以便在各处都可以使用 
			// $user = \Yii::createObject([
			// 	'class'    => User::className(),
			// 	'scenario' => 'create',
			// ]);
			// $data['User']['email'] = $this->mail;
			// $data['User']['username'] = $this->phone;
			// $data['User']['password'] = $this->password;

			// $user->load($data);
			// $ret = $user->create();
        }else{
			// $user = User::find()->where(['email'=>$this->mail])->one();	
			// if($user){
			// 	$user->username = $this->phone;
			// 	$user->save();
			// }
		}

        $this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);

        return parent::beforeSave($insert);
    }//}}}


    // 验证密码 
    public function validateConPassword($attr){//{{{
        if(! Yii::$app->getSecurity()->validatePassword($this->$attr, $this->password)){

            $this->addError($attr, "两次密码不一致");
        }
    }//}}}

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app.member', 'Name'),
            'phone' =>  Yii::t('app.member', 'Phone'),
            'mail' => Yii::t('app.member', 'Mail'),
            'password' => Yii::t('app.member', 'Password'),
            'address' => Yii::t('app.member', 'Address'),
            'position' => Yii::t('app.member', 'Position'),
            'group' => Yii::t('app.member', 'Group'),
            'dist_id' => Yii::t('app.member', 'Dist ID'),
            'type' => Yii::t('app.member', 'Type'),
            'desc' => Yii::t('app', 'Desc'),
            'status' => Yii::t('app', 'Status'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'gender' => Yii::t('app.member', 'Gender'),
            'company' => Yii::t('app.member', 'Company'),
            'openId' => Yii::t('app.member', 'openId'),
        ];
    }


    public function login($phone, $password){//{{{
        $cookies = Yii::$app->response->cookies;

        $query = Member::find(); 

        $model = $query->where(['phone'=>$phone,'status'=>1])->one();

        if($model){
            if(Yii::$app->getSecurity()->validatePassword($password, $model->password)){
            
                $session = new Session;
                $session->open();
                $session->set('member', ['id'=>$model->id, 'phone'=>$model->phone, 'name'=>$model->name, 'email'=>$model->mail,'company'=>$model->company]);
                // 存入 cookies
                $cookies->add(new \yii\web\Cookie([
                                'name' => 'member',
                                'value' => $model->phone,
                                'expire'=> time()+ 30*24*3600
                            ]));
                $cookies->add(new \yii\web\Cookie([
                                'name' => 'member_password',
                                'value' => $password,
                                'expire'=> time()+ 30*24*3600
                            ]));
            }else{

                $this->addError('password', "密码不正确");
                return false;
            }
        }else{
            $this->addError('password', "手机号不存在或已被禁用");
            return false;
        }
        return $model;
    }//}}}


    public function loginAjax($phone, $password){//{{{
        $query = Member::find(); 

        $model = $query->where(['phone'=>$phone])->one();

        if($model){        
            if(!Yii::$app->getSecurity()->validatePassword($password, $model->password)){
            
                $this->addError('member-password', "密码不正确");
                return false;
            }
        }else{
            $this->addError('member-phone', "手机号不存在或已被禁用");
            return false;
        }
        return $model;
    }//}}}

}
